<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true"  v-show="showSearch" label-width="68px" :rules="rules">
      <el-form-item label="车间" prop="fab">
        <el-select v-model="queryParams.fab" placeholder="请选择车间" @change="getFactoryAreaIdList(queryParams.fab)"
          clearable>
          <el-option v-for="dict in factoryIdOptions" :key="dict.value" :label="dict.label" :value="dict.value" />
        </el-select>
      </el-form-item>
      <el-form-item label="制造区域" prop="area">
        <el-select v-model="queryParams.area" placeholder="请选择制造区域" @change="getProductionTypeIdList(queryParams.area)"
          clearable>
          <el-option v-for="dict in factoryAreaIdOptions" :key="dict.value" :label="dict.label" :value="dict.value" />
        </el-select>
      </el-form-item>
      <el-form-item label="制造类型" prop="process">
        <el-select v-model="queryParams.process" placeholder="请选择制造类型" @change="getMachineTypeIdList(queryParams.process)" clearable>
          <el-option v-for="dict in listProductionTypeOptions" :key="dict.value" :label="dict.label"
            :value="dict.value" />
        </el-select>
      </el-form-item>
      <!-- <el-form-item label="设备类型" prop="eqpType">
        <el-select v-model="queryParams.eqpType" placeholder="请选择设备类型" @change="getlistMachineGroupOptions(queryParams.eqpType)"
          clearable>
          <el-option v-for="dict in listMachineTypeIdListOptions" :key="dict.value" :label="dict.label"
            :value="dict.value" />
        </el-select>
      </el-form-item> -->
      <el-form-item label="父设备" prop="machineGroup">
        <el-select v-model="queryParams.machineGroup" placeholder="请选择父设备"
          @change="getByToyMachineIdMachineIdList(queryParams.machineGroup)" clearable>
          <el-option v-for="dict in listMachineTypeIdListOptions" :key="dict.value" :label="dict.label" :value="dict.value" />
        </el-select>
      </el-form-item>
      <el-form-item label="设备ID" prop="machineId">
        <el-select v-model="queryParams.machineId" placeholder="请选择设备ID" clearable multiple>
          <el-option v-for="dict in MachineIdListOptions" :key="dict.value" :label="dict.label" :value="dict.value" />
        </el-select>
      </el-form-item>
      <el-form-item label="现状态" prop="eptStatus">
        <el-select v-model="queryParams.eptStatus" placeholder="请选择现状态" clearable @change="getDescriptionListOptionsList" multiple>
          <el-option v-for="dict in eptStatusListOptions" :key="dict.value" :label="dict.label" :value="dict.value" />
        </el-select>
      </el-form-item>
    <el-form-item label="状态描述" prop="description">
        <el-select v-model="queryParams.description" placeholder="请选择状态描述" clearable multiple>
          <el-option v-for="dict in descriptionListOptions" :key="dict.value" :label="dict.label" :value="dict.value" />
        </el-select>
      </el-form-item>
      <el-form-item label="查询时间">
        <WeekTimePicker type="datetime" v-model="queryParams.startTime" :clearable="false" style="width: 170px" />
        <span style="margin: 0px 6px;">~</span>
        <WeekTimePicker type="datetime" v-model="queryParams.endTime" :clearable="false" style="width: 170px" />
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="warning" plain icon="Download" @click="handleExport"
          v-hasPermi="['timeAnalysis:machineHistory:export']">导出</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList">
        <el-form-item>
          <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
          <el-button icon="Refresh" @click="resetQuery">重置</el-button>
        </el-form-item>
      </right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="machineHistoryList" @selection-change="handleSelectionChange"
      style="height: calc(100% - 200px);">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="父设备" align="center" prop="machineGroup" />
      <el-table-column label="设备ID" align="center" prop="machineId" />
      <el-table-column label="变更事件" align="center" prop="eventName" />
      <el-table-column label="开始时间" align="center" prop="createTime" width="180">
      </el-table-column>
      <el-table-column label="结束时间" align="center" prop="endTime" width="180">
      </el-table-column>
      <el-table-column label="持续时长" align="center" prop="keepTime" />
      <el-table-column label="停机区分" align="center" prop="shutdownType"/> // 新增字段
      <el-table-column label="前状态" align="center" prop="preEptStatus" />
      <el-table-column label="现状态" align="center" prop="eptStatus" />
      <el-table-column label="设备硬件状态" align="center" prop="hardwareStatus" />
      <el-table-column label="设备通讯状态" align="center" prop="processStatus" />
      <el-table-column label="RCode" align="center" prop="rcode" />
      <el-table-column label="RCode描述" align="center" prop="description" />
      <el-table-column label="备注信息" align="center" prop="remak" />
      <el-table-column label="报警号" align="center" prop="alarmIds" />
      <el-table-column label="等级" align="center" prop="level" />
      <el-table-column label="来源" align="center" prop="fromId" />
      <el-table-column label="父设备" align="topId" prop="topId"/> // 新增字段
      <el-table-column label="损失类型" align="center" prop="modelType" />
      <el-table-column label="设备类型" align="center" prop="machineType" />
      <el-table-column label="报警ID" align="center" prop="alarmId" />
      <el-table-column label="报警等级" align="center" prop="alarmLevel" />
      <el-table-column label="发报警时间" align="center" prop="alarmSendTime" />
      <el-table-column label="读报警时间" align="center" prop="alarmReadTime" />
      <el-table-column label="消报警时间" align="center" prop="alarmEndTime" />
      <el-table-column label="报警文本" align="center" prop="alarmText" />
      <el-table-column label="读报警损失" align="center" prop="readLossTime" />
      <el-table-column label="消报警损失" align="center" prop="clearLossTime" />
    </el-table>

    <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNum" v-model:limit="queryParams.pageSize"
      @pagination="getList" />

    <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form ref="machineHistoryRef" :model="form" label-width="80px">
        <el-table-column label="开始时间" align="center" prop="createTime" width="180">
          <template #default="scope">
            <span>{{ parseTime(scope.row.createTime, '{y}-{m}-{d}') }}</span>
          </template>
        </el-table-column>
        <el-table-column label="结束时间" align="center" prop="endTime" width="180">
          <template #default="scope">
            <span>{{ parseTime(scope.row.endTime, '{y}-{m}-{d}') }}</span>
          </template>
        </el-table-column>
        <el-table-column label="持续时长" align="center" prop="keepTime" />
        <el-table-column label="设备ID" align="center" prop="machineId">
        </el-table-column>
        <el-table-column label="设备状态" align="center" prop="eptStatus" />
        <el-table-column label="RCode" align="center" prop="rcode" />
        <el-table-column label="报警号" align="center" prop="alarmIds" />
        <el-table-column label="备注信息" align="center" prop="remak" />
        <el-table-column label="父设备" align="center" prop="machineGroup" />
        <el-table-column label="状态变更类型" align="center" prop="eventName" />
        <el-table-column label="设备通讯状态" align="center" prop="processStatus" />
        <el-table-column label="设备硬件状态" align="center" prop="hardwareStatus" />
        <el-table-column label="等级" align="center" prop="level" />
        <el-table-column label="来源" align="center" prop="fromId" />
        <el-table-column label="前状态" align="center" prop="preEptStatus" />
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="MachineHistory">
  import { listMachineHistory, getMachineHistory, delMachineHistory, addMachineHistory, updateMachineHistory } from "@/api/timeAnalysis/machineHistory"

  import moment from 'moment'
  import request from '@/utils/request'
  const { proxy } = getCurrentInstance()

  const machineHistoryList = ref([])
  const open = ref(false)
  const loading = ref(true)
  const showSearch = ref(true)
  const ids = ref([])
  const single = ref(true)
  const multiple = ref(true)
  const total = ref(0)
  const title = ref("")

  const data = reactive({
    form: {},
    queryParams: {
      pageNum: 1,
      pageSize: 20,
      startTime: moment().format('YYYY-MM-DD HH:mm:ss'),
      endTime: moment().add(1, 'days').format('YYYY-MM-DD HH:mm:ss'),
      machineId: null,
      eptStatus: null,
      eventName: null,
      fab: null,
      area: null,
      process: null,
      eqpType: null,
      description: null,
      id: null,
      keepTime: null,
      rcode: null,
      alarmIds: null,
      remak: null,
      machineGroup: null,
      processStatus: null,
      hardwareStatus: null,
      level: null,
      fromId: null,
      preEptStatus: null,
      process: null,
      eqpType: null,
      area: null
    },
    rules: {
      machineGroup: [
        { required: true, message: "父设备不能为空", trigger: "blur" }
      ]
    }
  })
  const factoryIdOptions = ref([])
  const factoryAreaIdOptions = ref([])
  const listProductionTypeOptions = ref([])
  const listMachineTypeIdOptions = ref([])
  const listMachineTypeIdListOptions = ref([])
  const MachineIdListOptions = ref([])
  const eptStatusListOptions = ref([])
  const descriptionListOptions = ref([])

  const getFactoryIdListInfo = () => {
    return request({
      url: '/parameter/getFactoryIdList/',
      method: 'get'
    })
  }
  const getFactoryIdList = () => {
    factoryIdOptions.value = []
    getFactoryIdListInfo().then((res) => {
      res.rows.forEach(item => {
        factoryIdOptions.value.push({
          label: item,
          value: item
        })
      })
    })
  }
  getFactoryIdList()
  const getFactoryAreaIdListInfo = (factoryId) => {
    return request({
      url: '/parameter/getFactoryAreaIdList/?factoryId=' + factoryId,
      method: 'get'
    })
  }
  const getFactoryAreaIdList = (factoryId) => {
    factoryAreaIdOptions.value = []
    getFactoryAreaIdListInfo(factoryId).then((res) => {
      res.rows.forEach(item => {
        factoryAreaIdOptions.value.push({
          label: item,
          value: item
        })
      })
    })
  }
  const getProductionTypeIdListInfo = (factoryAreaId) => {
    return request({
      url: '/parameter/getProductionTypeIdList/?factoryAreaId=' + factoryAreaId,
      method: 'get'
    })
  }
  const getProductionTypeIdList = (factoryAreaId) => {
    listProductionTypeOptions.value = []
    getProductionTypeIdListInfo(factoryAreaId).then((res) => {
      res.rows.forEach(item => {
        listProductionTypeOptions.value.push({
          label: item,
          value: item
        })
      })
    })
  }

  const getgetMachineTypeIdListInfo = (productionTypeId) => {
    return request({
      url: '/parameter/getMachineGroupByMachineTypeId/?machineType=' + productionTypeId,
      method: 'get'
    })
  }
  const getMachineTypeIdList = (productionTypeId) => {
    listMachineTypeIdListOptions.value = []
    getgetMachineTypeIdListInfo(productionTypeId).then((res) => {
      res.rows.forEach(item => {
        listMachineTypeIdListOptions.value.push({
          label: item,
          value: item
        })
      })
    })
  }
  const getlistMachineInfo = (machineTypeId) => {
    return request({
      url: '/parameter/getMachineIdList/?machineTypeId=' + machineTypeId,
      method: 'get'
    })
  }
  const getlistMachineGroupOptions = (machineTypeId) => {
    listMachineTypeIdOptions.value = []
    getlistMachineInfo(machineTypeId).then((res) => {
      res.rows.forEach(item => {
        listMachineTypeIdOptions.value.push({
          label: item,
          value: item
        })
      })
    })
  }
  const getByToyMachineIdMachineIdListtInfo = (machineGroup) => {
    return request({
      url: '/parameter/getMachineIdBymachineGroup/?machineGroup=' + machineGroup,
      method: 'get'
    })
  }
  const getByToyMachineIdMachineIdList = (machineGroup) => {
    MachineIdListOptions.value = []
    queryParams.value.machineId = []
    getByToyMachineIdMachineIdListtInfo(machineGroup).then((res) => {
      res.rows.forEach(item => {
        MachineIdListOptions.value.push({
          label: item,
          value: item
        })
      })
    })
  }
  const getEptStatusListOptionsListtInfo = () => {
    return request({
      url: '/parameter/getmachineStatus/',
      method: 'get'
    })
  }
  const getEptStatusListOptionsList = () => {
    eptStatusListOptions.value = []
    getEptStatusListOptionsListtInfo().then((res) => {
      res.rows.forEach(item => {
        eptStatusListOptions.value.push({
          label: item,
          value: item
        })
      })
    })
  }
  getEptStatusListOptionsList()
  const getDescriptionListOptionsInfo = (machineStatus) => {
    return request({
      url: '/parameter/getDescription/?machineStatus=' + machineStatus,
      method: 'get'
    })
  }
  const getDescriptionListOptionsList = (machineStatus) => {
    if(machineStatus.length === 0){
      return
    }
    descriptionListOptions.value = []
    queryParams.value.description = null
    getDescriptionListOptionsInfo(machineStatus).then((res) => {
      res.rows.forEach(item => {
        descriptionListOptions.value.push({
          label: item.description,
          value: item.descriptionCode
        })
      })
    })
  }

  const { queryParams, form, rules } = toRefs(data)

  function getList() {
    loading.value = true

    queryParams.value.startTime = moment(queryParams.value.startTime).format('YYYY-MM-DD HH:mm:ss')
    queryParams.value.endTime = moment(queryParams.value.endTime).format('YYYY-MM-DD HH:mm:ss')

    listMachineHistory(queryParams.value).then(response => {
      machineHistoryList.value = response.rows
      total.value = response.total
      loading.value = false
    })
  }

  function cancel() {
    open.value = false
    reset()
  }

  function reset() {
    form.value = {
      id: null,
      createTime: null,
      endTime: null,
      keepTime: null,
      machineId: [],
      eptStatus: null,
      rcode: null,
      alarmIds: null,
      remak: null,
      machineGroup: null,
      eventName: null,
      processStatus: null,
      hardwareStatus: null,
      level: null,
      fromId: null,
      preEptStatus: null,
      process: null,
      eqpType: null
    }
    proxy.resetForm("machineHistoryRef")
  }

  function handleQuery() {
    proxy.$refs.queryRef.validate((val) => {
      if(val) {
        queryParams.value.pageNum = 1
        getList()
      }
    })
  }

  function resetQuery() {
    proxy.resetForm("queryRef")
    handleQuery()
  }

  function handleSelectionChange(selection) {
    ids.value = selection.map(item => item.id)
    single.value = selection.length != 1
    multiple.value = !selection.length
  }

  function handleAdd() {
    reset()
    open.value = true
    title.value = "添加EPT设备履历"
  }

  function handleUpdate(row) {
    reset()
    const _id = row.id || ids.value
    getMachineHistory(_id).then(response => {
      form.value = response.data
      form.value.machineId = form.value.machineId.split(",")
      open.value = true
      title.value = "修改EPT设备履历"
    })
  }

  function submitForm() {
    proxy.$refs["machineHistoryRef"].validate(valid => {
      if (valid) {
        form.value.machineId = form.value.machineId.join(",")
        if (form.value.id != null) {
          updateMachineHistory(form.value).then(response => {
            proxy.$modal.msgSuccess("修改成功")
            open.value = false
            getList()
          })
        } else {
          addMachineHistory(form.value).then(response => {
            proxy.$modal.msgSuccess("新增成功")
            open.value = false
            getList()
          })
        }
      }
    })
  }

  function handleDelete(row) {
    const _ids = row.id || ids.value
    proxy.$modal.confirm('是否确认删除EPT设备履历编号为"' + _ids + '"的数据项？').then(function () {
      return delMachineHistory(_ids)
    }).then(() => {
      getList()
      proxy.$modal.msgSuccess("删除成功")
    }).catch(() => { })
  }

  /** 导出按钮操作 */
  function handleExport() {
    proxy.download('timeAnalysis/machineHistory/export', {
      ...queryParams.value
    }, `machineHistory_${new Date().getTime()}.xlsx`)
  }

  getList()
</script>

